package com.luhuiguo.cms.server.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.luhuiguo.cms.server.service.MapperService;
import com.luhuiguo.cms.shared.model.UserModel;
import com.luhuiguo.cms.shared.rpc.GetAuthentication;
import com.luhuiguo.cms.shared.rpc.GetAuthenticationResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;

@Component
public class GetAuthenticationHandler implements ActionHandler<GetAuthentication, GetAuthenticationResult> {

    @Autowired
    private MapperService mapperService;

    @Override
    public GetAuthenticationResult execute(GetAuthentication action, ExecutionContext context) throws ActionException {

        boolean authenticated = false;
        UserModel user = null;

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (null != auth) {
            authenticated = auth.isAuthenticated();

            user = mapperService.map(auth.getPrincipal(), UserModel.class);
        }

        return new GetAuthenticationResult(authenticated, user);
    }

    @Override
    public Class<GetAuthentication> getActionType() {
        return GetAuthentication.class;
    }

    @Override
    public void rollback(GetAuthentication action, GetAuthenticationResult result, ExecutionContext context)
            throws ActionException {

    }

}
